#coding:gbk

from config import *
from debug import *
import smartcard as _sc
import os.path

g_eep_obj = None

def eep_init():
    global g_eep_obj
    fileName = "eep.dat"
    if os.path.exists(fileName):
        g_eep_obj = open(fileName, "r+b")
    else:
        g_eep_obj = open(fileName, "w+b")
        data = '\x00' * EEP_IMAGE_SIZE
        g_eep_obj.write(data)
        g_eep_obj.flush()
    eep_recover()

def eep_read_page(addr):
    global g_eep_obj
    g_eep_obj.seek(addr)
    data = g_eep_obj.read(EEP_PAGE_SIZE)
    return data

def eep_write_physic_page(addr, data):
    global g_eep_obj
    g_eep_obj.seek(addr)
    g_eep_obj.write(data)
    g_eep_obj.flush()

'''
flag section data
4  bytes flag
4  bytes addr
20 bytes sha1
'''
def write_flag(addr, isSet):
    FLAG = EEP_FLAG1 if isSet else EEP_FLAG2
    D12 = FLAG + int2bytes(addr)
    D3 = _sc.sha1(D12)
    D123 = D12 + D3
    D4 = '\x00' * (EEP_PAGE_SIZE - len(D123))
    D1234 = D123 + D4
    eep_write_physic_page(EEP_BAK_FLAG_ADDR, D1234)

def eep_write_page(addr, data):
    #1. read old data and back up it
    old_data = eep_read_page(addr)
    eep_write_physic_page(EEP_BAK_DATA_ADDR, old_data)
    #2. write flag page
    write_flag(addr, True)
    #3. write new data
    eep_write_physic_page(addr, data)
    #4. clear flag
    write_flag(addr, False)

def eep_recover():
    flag_data = eep_read_page(EEP_BAK_FLAG_ADDR)
    FLAG, addr, H1 = flag_data[:4], bytes2int(flag_data[4:8]), flag_data[8:28]
    H2 = _sc.sha1(flag_data[:8])
    if FLAG == EEP_FLAG1 and H1 == H2:
        bak_data = eep_read_page(EEP_BAK_DATA_ADDR)
        eep_write_physic_page(addr, bak_data)
        write_flag(addr, False)

def main():
    pass

if __name__ == '__main__':
    main()

